/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * HDRRadianceMapConstructor.java
 *
 * Created on 09.12.2008, 13:57:24
 */
package hdr_plugin;

import hdr_plugin.Exceptions.TypeNotSupportedException;
import hdr_plugin.radiance.DebevecRadiance;
import hdr_plugin.radiance.RadianceMapConstructor;
import hdr_plugin.radiance.RobertsonRadiance;
import hdr_plugin.response.ResponseFunction;
import hdr_plugin.tonemapping.SimpleToneMapper;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.NewImage;
import ij.io.OpenDialog;
import ij.process.FloatProcessor;
import java.awt.image.ColorModel;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alexander Heidrich
 */
public class HDRRadianceMapConstructor extends java.awt.Frame {

    private ResponseFunction in;

    private void initStackList() {
        chcStack.add("Please Select ...");
        int[] imgList = WindowManager.getIDList();
        String[] imgTitles = new String[imgList.length];
        for (int i = 0; i < imgList.length; i++) {
            ImagePlus imp = WindowManager.getImage(imgList[i]);
            if (imp != null) {
                imgTitles[i] = imp.getTitle();
            } else {
                imgTitles[i] = "";
            }
        }
        for (String title : imgTitles) {
            chcStack.add(title);
        }
        chcStack.select(0);
    }

    /** Creates new form HDRRadianceMapConstructor */
    public HDRRadianceMapConstructor() {
        initComponents();
        initStackList();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lblLogo = new javax.swing.JLabel();
        pnlContent = new java.awt.Panel();
        txtExpTimes = new java.awt.TextField();
        lblCurve = new java.awt.Label();
        lblCurve_ = new java.awt.Label();
        lblStack = new java.awt.Label();
        chcStack = new java.awt.Choice();
        pnlButtons = new java.awt.Panel();
        btnLoad = new java.awt.Button();
        btnRadiance = new java.awt.Button();
        btnCancel = new java.awt.Button();
        btnHelp = new java.awt.Button();

        setBackground(new java.awt.Color(255, 255, 255));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        setLayout(new java.awt.GridBagLayout());

        lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/hdr_plugin/resources/log.jpg"))); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        add(lblLogo, gridBagConstraints);

        pnlContent.setLayout(new java.awt.GridBagLayout());

        txtExpTimes.addTextListener(new java.awt.event.TextListener() {
            public void textValueChanged(java.awt.event.TextEvent evt) {
                txtExpTimestest(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 200;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pnlContent.add(txtExpTimes, gridBagConstraints);

        lblCurve.setText("Camera Response Function:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pnlContent.add(lblCurve, gridBagConstraints);

        lblCurve_.setEnabled(false);
        lblCurve_.setText("none");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 100;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pnlContent.add(lblCurve_, gridBagConstraints);

        lblStack.setText("HDR Stack:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pnlContent.add(lblStack, gridBagConstraints);

        chcStack.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                chcStackItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 100;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(1, 1, 1, 1);
        pnlContent.add(chcStack, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        add(pnlContent, gridBagConstraints);

        pnlButtons.setLayout(new java.awt.GridBagLayout());

        btnLoad.setLabel("Load Response Function...");
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlButtons.add(btnLoad, gridBagConstraints);

        btnRadiance.setEnabled(false);
        btnRadiance.setLabel("Create Radiance Map");
        btnRadiance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRadianceActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlButtons.add(btnRadiance, gridBagConstraints);

        btnCancel.setLabel("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlButtons.add(btnCancel, gridBagConstraints);

        btnHelp.setFont(new java.awt.Font("Lucida Grande", 1, 13));
        btnHelp.setLabel("Help");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        pnlButtons.add(btnHelp, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
        add(pnlButtons, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
        this.dispose();
    }//GEN-LAST:event_exitForm

    private void btnRadianceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRadianceActionPerformed
        ImagePlus imp = WindowManager.getImage(chcStack.getSelectedItem());
                String[] values = txtExpTimes.getText().split(",");
        double[] expTimes = new double[values.length];
        for (int i = 0; i < expTimes.length; i++) {
            expTimes[i] = new Double(values[i].trim().replaceAll(" ", ""));
        }

        RadianceMapConstructor radiance = new RobertsonRadiance(imp,in,expTimes);
        try {
            FloatProcessor floatP = new FloatProcessor(imp.getWidth(),imp.getHeight(),radiance.calcRadiance(0));
            ImagePlus newImage = new ImagePlus("Radiance Map", floatP);
            newImage.show();
        } catch (TypeNotSupportedException ex) {
            Logger.getLogger(HDRRadianceMapConstructor.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_btnRadianceActionPerformed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        OpenDialog od = new OpenDialog("Open Response Curve", null, "*.rf");
        String dir = od.getDirectory();
        String name = od.getFileName();
        if (dir == null || name == null) {
            return;
        }
        InputStream reader = null;
        try {
            reader = new FileInputStream(dir + name);
            ObjectInputStream o = new ObjectInputStream(reader);
            in = (ResponseFunction) o.readObject();
            lblCurve_.setText(name);
            // enable the radiance button if also a stack is selected
            if (chcStack.getSelectedIndex() != 0) {
                btnRadiance.setEnabled(true);
            } else {
                btnRadiance.setEnabled(false);
            }
        // TODO Exception handling!
        } catch (IOException ex) {
            IJ.error("File could not be read!");
            //btnRadiance.setEnabled(false);
            return;
        } catch (ClassNotFoundException ex) {
            IJ.error("File could not be read!");
            //btnRadiance.setEnabled(false);
            return;
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }//GEN-LAST:event_btnLoadActionPerformed

    private void chcStackItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chcStackItemStateChanged
        if (((java.awt.Choice) evt.getSource()).getSelectedIndex() != 0 && in != null) {
            btnRadiance.setEnabled(true);
        } else {
            btnRadiance.setEnabled(false);
        }
    }//GEN-LAST:event_chcStackItemStateChanged

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void txtExpTimestest(java.awt.event.TextEvent evt) {//GEN-FIRST:event_txtExpTimestest
        // TODO add your handling code here:
}//GEN-LAST:event_txtExpTimestest

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.Button btnCancel;
    private java.awt.Button btnHelp;
    private java.awt.Button btnLoad;
    private java.awt.Button btnRadiance;
    private java.awt.Choice chcStack;
    private java.awt.Label lblCurve;
    private java.awt.Label lblCurve_;
    private javax.swing.JLabel lblLogo;
    private java.awt.Label lblStack;
    private java.awt.Panel pnlButtons;
    private java.awt.Panel pnlContent;
    private java.awt.TextField txtExpTimes;
    // End of variables declaration//GEN-END:variables
}
